package com.authine.cloudpivot.ext.applicationservice.executor;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.PlatformConst;
import com.authine.cloudpivot.ext.dto.JobDto;
import com.authine.cloudpivot.ext.enums.system.TriggerMetaStatusEnum;
import com.authine.cloudpivot.ext.service.ZhendeService;
import com.authine.cloudpivot.ext.service.impl.ZhendeServiceImpl;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.vo.TempOrderReceiptVo;
import com.authine.cloudpivot.ext.vo.zhende.ZhenDeReceiptModel;
import com.authine.hermes.app.launcher.service.ApplicationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.List;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * 振德 定时任务回调批量收货
 */
@Path("ZhenDeReceiptOrderPushJobExecutor")
@Slf4j
public class ZhenDeReceiptOrderPushJobExecutor extends ApplicationService {

    private ZhendeService zhendeService = new ZhendeServiceImpl();

    /**
     * 定时任务回调批量收货
     *
     * @param dto
     */
    @Path("goodsReceiptBatch")
    @POST
    @Operation(summary = "定时任务回调批量收货", tags = CUSTOM_SERVICE)
    public void goodsReceiptBatch(@Parameter JobDto dto) {
        // 设置token认证信息
        RequestContext.get().setCorpLoginId(PlatformConst.corpLoginId);
        RequestContext.get().setLoginId(PlatformConst.loginId);
        RequestContext.get().setLoginName(PlatformConst.loginName);

        log.info("===================定时任务开始，回调批量收货，入参{}===================", JSONObject.toJSONString(dto));
        // 通过询价单获取询价商品
        // 获取：振德客户（Sets.newHashSet("河南振德医疗用品有限公司", "许昌振德医用敷料有限公司", "振德医疗用品股份有限公司", "许昌正德医疗用品有限公司", "绍兴好士德医疗用品有限公司")） & 待收货状态 & (erpPo!=xinjidi) 的客户订单List<po> TODO 张天赐
        List<String> idsStr = zhendeService.getErpPoByZhenDeToReceive();
        log.warn("=查询振德订单商品未收货数据：{}", idsStr);
        // 请求punchout 振德查询订单商品收货信息 return:(ErpPo、Set<sku>)
        ZhenDeReceiptModel data = pushReceiptToZhenDe(idsStr);
        log.warn("请求punchout查询振德订单状态返回信息：{}", data);

        TempOrderReceiptVo result = null;
        try {
            // 执行收货操作
            result = zhendeService.zhenDeGoodsReceiptBatch(data);
        } catch (Exception e) {
            log.error("振德批量收货执行报错，错误信息：{}", e);
        }
        // 这里处理的什么？收货后的事件？
        if (null != result) {
//            applicationEventPublisher.publishEvent(new
//                    OrderRemoteSyncEvent(this, busProperties.getId(),
//                    "**", OrderRemoteSyncEventParam.builder()
//                    .type(OrderSyncEventTypeEnum.GoodsReceipt).orderGoodsAcceptIds(result.getReceivedIds()).build()));
        }
        log.info("===================定时任务结束，修改询价状态为结束，修改结果：{}===================", JSONObject.toJSONString(result));

        // 修改任务触发器状态为已执行
        JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_TRIGGER_META).putFieldAndVal("trigger_status", TriggerMetaStatusEnum.EXECUTED.id)
                .eq("id", dto.getTriggerMetaId()).update();
        // 清除登录信息
        RequestContext.clear();
    }

    public ZhenDeReceiptModel pushReceiptToZhenDe(List<String> orderGoodIdList) {
        if (orderGoodIdList == null || orderGoodIdList.isEmpty()) {
            return null;
        }
        ZhenDeReceiptModel zhenDeReceiptModel = null;
        try {
            for(String orderGoodsId: orderGoodIdList) {
                zhenDeReceiptModel = zhendeService.receiptOrderPush1(orderGoodsId);
            }
        } catch (Exception e) {
            log.error("[push-zhende] end:执行类：{},执行方法：pushOrderUpdate（推送振德收货）失败，失败信息：{}",this.getClass().getName(), e);
        }
        log.warn("[push-zhende] end:执行类：{},执行方法：pushOrderUpdate（推送振德收货）", this.getClass().getName());
        return zhenDeReceiptModel;
    }

}
